package cc.inq.db.tools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

public class WinUtil {
	
	/**
	 * 设置窗口位于屏幕中间
	 * 
	 * @param display
	 *            设备
	 * @param shell
	 *            要调整位置的窗口对象
	 */
	public static void center(Display display, Shell shell) {
		Rectangle bounds = display.getPrimaryMonitor().getBounds();
		Rectangle rect = shell.getBounds();
		int x = bounds.x + (bounds.width - rect.width) / 2;
		int y = bounds.y + (bounds.height - rect.height) / 2;
		shell.setLocation(x, y);
	}

	/**
	 * 弹出消息
	 * 
	 * @author firefly
	 * @scene 2019年3月1日
	 * @param shell
	 * @param type
	 * @param title
	 * @param msg
	 */
	public static void showMsg(Shell shell, int type, String title, String msg) {
		MessageBox dialog = new MessageBox(shell, type);
		dialog.setText(title);
		dialog.setMessage(msg);
		dialog.open();
	}

	/**
	 * 保存文件
	 * @author firefly
	 * @scene 2019年3月1日
	 * @return
	 */
	public static OutputStreamWriter makeFile(String fileName) {
		// 数据导出
		FileDialog fileDialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE);
		fileDialog.setFileName(fileName);
		String pathName = fileDialog.open();
		if (pathName == null) {
			return null;
		}
		OutputStreamWriter osw = null;
		try {
			FileOutputStream fos = new FileOutputStream(pathName);
			osw = new OutputStreamWriter(fos);
		} catch (FileNotFoundException e) {
			WinUtil.showMsg(Display.getCurrent().getActiveShell(), SWT.OK | SWT.ICON_WARNING, "无法导出文件", e.getMessage());
		}
		return osw;
	}
}